<!-- 金融产品 -->
<template>
  <div>
    <div v-if="scene==0">
      <ContainerSlot>
        <!-- 搜索 -->
        <template slot="searchModule">
          <SearchForm :label-width="labelWidth" :form-config="formConfig" :form-data="formData" :slot-list="slotList">
            <template slot="searchBtn">
              <el-button type="primary" @click.prevent="search()">查询</el-button>
            </template>
          </SearchForm>
        </template>
        <!-- 添加 -->
        <template slot="operationModule">
          <el-button type="primary" plain @click="addExpert">添加</el-button>
        </template>
        <!-- 内容 -->
        <template slot="contentModule">
          <div v-show="financialProductList.length>0" class="content">
            <div v-for="item in financialProductList" :key="item.productId" class="contentItem">
              <div class="header">
                <div class="img">
                  <img
                    v-show="item.imgList.length>0"
                    :src="item.imgList[0] && item.imgList[0].productImgUrl"
                    alt=""
                  >
                </div>
                <div class="mask">{{ item.productTitle }}</div>
              </div>
              <div class="center">{{ item.productContent }}</div>
              <div class="footer">
                <div class="operation">
                  <el-button type="primary" plain @click="goInfo(item)">查看详情</el-button>
                  <el-button type="primary" plain @click="edit(item)">修改</el-button>
                  <el-button type="primary" @click="del(item)">删除</el-button>
                </div>
              </div>
              <div class="decoration" />
            </div>
          </div>
          <div v-show="financialProductList.length==0" class="nodata">
            暂无数据~
          </div>
        </template>
        <template slot="footerModule">
          <el-pagination
            :current-page="currentPage"
            background
            :page-size="pageSize"
            :page-sizes="[10, 20, 30]"
            layout=" prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </template>
      </ContainerSlot>
      <el-dialog :close-on-click-modal='false' :title="`${title}金融产品`" :visible.sync="dialogFormVisible" top="30vh" @close="close">
        <el-form ref="ruleForm" :inline="true" :model="form" :rules="rules">
          <el-form-item label="金融名称：" prop="productTitle" :label-width="formLabelWidth">
            <el-input v-model="form.productTitle" autocomplete="off" />
          </el-form-item>
          <el-form-item label="金融介绍：" :label-width="formLabelWidth" prop="productContent">
            <el-input v-model="form.productContent" autocomplete="off" />
          </el-form-item>
          <!-- prop="imgUrl" -->
          <el-form-item label="介绍图片：" prop="url" :label-width="formLabelWidth">
            <el-upload
              ref="upload"
              :on-change="handleChange"
              :http-request="handlerFile"
              action=""
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :file-list="spuImageList"
              :limit="limit"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog :close-on-click-modal='false' :visible.sync="show">
              <img width="100%" :src="dialogImageUrl">
            </el-dialog>
          </el-form-item>
          <el-form-item label="设置类型：" prop="radio" :label-width="formLabelWidth">
            <el-radio-group v-model="form.radio">
              <el-radio :label="1">设为推荐产品</el-radio>
              <el-radio :label="2">设为精选产品</el-radio>
              <el-radio :label="3">设为普通产品</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div v-else>
      <ProductDetails :info-date="infoDate" @getScene="getScene" />
    </div>
  </div>
</template>

<script>
import ContainerSlot from '@/components/Container'
import SearchForm from '@/components/Form'
import ProductDetails from './components/product-details'
import DocumentApi from '@/api/document'
import config from '@/api/config'
import Api from '@/api/finance-insurance/financial-product-management/index'

export default {
  name: '',
  components: { ContainerSlot, SearchForm, ProductDetails },
  data () {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('金融名称不能为空'))
      } else {
        callback()
      }
    }
    var validateDesc = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('金融介绍不能为空'))
      } else {
        callback()
      }
    }
    return {
      // 金融产品列表
      financialProductList: [],
      limit: 10,
      scene: 0,
      title: '修改',
      editId: '',
      // 搜索框距离左侧位置
      labelWidth: '150px',
      // 表单配置
      formConfig: [
        {
          label: '金融产品名称',
          prop: 'name1',
          type: 'input',
          width: '150px'
        }
      ],
      // 查询按钮或重置
      slotList: [
        {
          slotName: 'searchBtn'
        }
      ],
      // 表单数据
      formData: {
        name1: ''
      },
      total: 1,
      currentPage: 1, // 当前页
      pageSize: 4,
      // 控制对话框显示隐藏
      dialogFormVisible: false,
      // 收集数据
      form: {
        productTitle: '',
        productContent: '',
        url: '',
        radio: 1,
        imgList: []
      },
      formLabelWidth: '120px',
      show: false,
      dialogImageUrl: '',
      spuImageList: [],
      rules: {
        productTitle: [
          { required: true, message: '请输入金融名称', trigger: 'blur' },
          { validator: validateName, trigger: 'change' }
        ],
        productContent: [
          { required: true, message: '请输入金融介绍', trigger: 'blur' },
          { validator: validateDesc, trigger: 'change' }
        ],
        url: [
          { required: true, message: '请选择图片', trigger: 'change' }
        ],
        radio: [
          { required: true, message: '请选择类型', trigger: ['change', 'blur'] }
        ]
      },
      infoDate: [],
      newImgList: []
    }
  },
  mounted() {
    // 获取分页列表
    this.getfinancialProductList()
  },
  methods: {
    // 获取分页列表
    async getfinancialProductList(pages = this.currentPage, keyword = '') {
      const params = {
        page: pages,
        size: this.pageSize,
        condition: {
          financialAndInsuranceFlag: 0,
          productTitle: keyword
        }
      }
      const res = await Api.queryFinancialProduct(params)
      if (res.data.code === 200) {
        this.financialProductList = res.data.data.content
        this.total = res.data.data.totalElements
        // this.spuImageList = res.data.data.content.imgList
      }
      // 数据总条数
    },
    // 搜索
    search() {
      this.currentPage = 1
      this.getfinancialProductList(1, this.formData.name1)
    },
    handleChange() {
      this.$refs.ruleForm.clearValidate('url')
    },
    getScene(e) {
      this.scene = e
      this.$route.meta.title = '金融产品'
    },
    // 当前页
    handleCurrentChange (e) {
      this.currentPage = e
      this.getfinancialProductList()
    },
    handleSizeChange (e) {
      this.pageSize = e
      this.getfinancialProductList()
    },
    // 添加显示dialog
    addExpert() {
      this.reset()
      this.title = '添加'
      this.dialogFormVisible = true
    },
    // 修改
    edit(item) {
      this.form.radio = 3
      if (item.recommendFlag) {
        this.form.radio = 1
      }
      if (item.choicenessFlag) {
        this.form.radio = 2
      }
      this.spuImageList = item.imgList
      this.spuImageList.forEach(item => {
        item.url = item.productImgUrl
        item.name = item.productImgUrl
      })
      this.newImgList = [...this.spuImageList]
      this.form.url = item.imgList[0] && item.imgList[0].productImgUrl
      this.form.productContent = item.productContent
      this.form.productTitle = item.productTitle
      this.form.imgList = item.imgList
      this.form = { ...this.form }
      this.title = '修改'
      this.dialogFormVisible = true
      this.editId = item.productId
    },
    reset() {
      this.form = {}
      this.spuImageList = []
    },
    // 删除
    del(item) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 请求
          const params = {}
          const res = await Api.del(params, item.productId)
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getfinancialProductList(this.financialProductList.length > 1 ? this.currentPage : this.currentPage - 1)
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleRemove(file, fileList) {
      this.newImgList = fileList
      this.spuImageList = fileList
      if (fileList.length === 0) {
        this.form.url = ''
      }
    },
    // 大图预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.show = true
    },
    // 自定义
    handlerFile(files) {
      // this.spuImageList = []
      const { file } = files
      const dataForm = new FormData()
      dataForm.append('file', file)
      dataForm.append('moduleType', 'INSURE')
      DocumentApi.getUploadUrl(dataForm).then(res => {
        this.uploading = false
        const filePath = res.data
        const url = config.webServiceUrl + filePath
        this.form.url = url
        this.spuImageList.push({ productImgUrl: url, url, name: url })
        this.newImgList = this.spuImageList
        // this.form.imgList.push(url)
        this.form.imgList = this.spuImageList
      })
    },
    // dialog确定添加或修改
    confirmAdd() {
      if (this.newImgList.length > 0) {
        console.log(this.newImgList.length, 'kk', this.form.url)

        this.$refs.ruleForm.validateField('url')
      }
      this.$refs.ruleForm.validate(async(valid) => {
        var params = {
          productTitle: this.form.productTitle,
          productContent: this.form.productContent,
          financialAndInsuranceFlag: 0,
          imgList: this.newImgList
        }
        if (this.form.radio === 1) {
          params['recommendFlag'] = true
          params['choicenessFlag'] = false
        } else if (this.form.radio === 2) {
          params['recommendFlag'] = false
          params['choicenessFlag'] = true
        } else {
          params['recommendFlag'] = false
          params['choicenessFlag'] = false
        }
        if (valid) {
          // 添加
          if (this.title === '添加') {
            const res = await Api.add(params)
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.dialogFormVisible = false
            } else if (res.data.code === 500) {
              this.$message({
                type: 'error',
                message: res.data.msg
              })
            }
          } else {
            // 修改
            params['productId'] = this.editId
            const res = await Api.edit(params)
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              // this.$refs.upload && this.$refs.upload.clearFiles()
              this.dialogFormVisible = false
              // this.getfinancialProductList()
            }
          }
        } else {
          return false
        }
        this.getfinancialProductList()
      })
    },
    close() {
      this.$refs.upload && this.$refs.upload.clearFiles()
      this.dialogFormVisible = false
      this.spuImageList = []
      this.newImgList = []
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields()
        this.reset()
      })
    },
    // 详情
    goInfo(item) {
      this.infoDate = item
      this.scene = 1
      this.$route.meta.title = '产品详情'
    }
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep .childModule {
    overflow: auto !important;
  }
  .content {
    width: 100%;
    height: 100%;
    .contentItem {
      position: relative;
      // height: 270px;
      float: left;
      margin-top: 4px;
      margin-right: 1%;
      margin-bottom: 23px;
      width: 24%;
      border-radius: 5px;
      box-shadow: 0px 0px 6px 1px rgba(4,128,251,0.5);
      .header {
        position: relative;
        width: 100%;
        height: 174px;
        border-radius: 5px 5px 0 0;
        //
        .img {
          width: 277px;
          height: 174px;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .mask {
          position: absolute;
          bottom: 0;
          width: 100%;
          height: 34px;
          font-size: 25px;
          font-weight: 500;
          color: #FFF;
          line-height: 34px;
          text-align: center;
          background: rgba(0,0,0,0.4);
        }
      }
      .center {
        display: inline-block;
        height: 35px;
        padding: 0 40px;
        width: 240px;
        margin: 10px 0;
        color: #6E6E6E;
        font-size: 16px;
        display: -webkit-box;
        overflow: hidden;
        white-space: wrap;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
      }
      .footer {
        height: 51px;
        background: #EDF6FF;
        .operation {
          height: 51px;
          display: flex;
          justify-content: flex-end;
          align-items: center;
          padding-right: 22px;
        }
      }
      .decoration {
      position: absolute;
      top: -2px;
      left: 50%;
      transform: translateX(-50%);
      width: 22px;
      height: 4px;
      background: #0480fb;
      z-index: 6;
    }
    }
  }
  .nodata {
    position: relative;
    width: 100%;
    // height: 100%;
    text-align: center;
    top: 50%;

  }
   ::v-deep .el-dialog__header {
    position: relative;
  }
  ::v-deep .el-dialog__headerbtn {
    position: absolute;
  //  top: 10px;
  top: 50%;
  transform: translateY(-50%);
  }
</style>
